import 'package:any_reader/views/moments/index.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:install_plugin/install_plugin.dart';

import '../public.dart';

class LayoutComponent extends StatefulWidget {
  LayoutComponent({Key key}) : super(key: key);
  @override
  _LayoutComponent createState() => new _LayoutComponent();
}

class _LayoutComponent extends State<LayoutComponent> {
  int _currentIndex = 0;
//  List<String> _listTitle = ['书库', '广场'];
  List<Widget> _listPage = [BookSheet()];
//  , MomentsPage()
  DateTime _lastPressed;
  String userAvatar = "https://s1.ax1x.com/2020/04/06/G6FKR1.jpg";
  var _pageController = new PageController(initialPage: 0);
  ThemeModel themeModel;

  Future<void> _showProgressNotification(
      maxProgress, nowProgress, percent) async {
    await Future.delayed(Duration(seconds: 1), () async {
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        '下载进度',
        'progress_channel',
        '用于通知下载进度',
        channelShowBadge: false,
        importance: Importance.Max,
        priority: Priority.High,
        onlyAlertOnce: true,
        showProgress: true,
        maxProgress: maxProgress,
        progress: nowProgress,
      );
      var iOSPlatformChannelSpecifics = IOSNotificationDetails();
      var platformChannelSpecifics = NotificationDetails(
          androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
      await AppUtils.flutterLocalNotificationsPlugin.show(
        0,
        '正在下载',
        percent,
        platformChannelSpecifics,
      );
    });
  }

  Future<void> initNotification() async {
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
    AppUtils.flutterLocalNotificationsPlugin = flutterLocalNotificationsPlugin;
    var initializationSettingsAndroid =
        AndroidInitializationSettings('@/mipmap/ic_launcher');
    var initializationSettingsIOS = IOSInitializationSettings();
    var initializationSettings = InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initNotification();

    FlutterStatusbarManager.setHidden(false);
    FlutterStatusbarManager.setFullscreen(false);
    FlutterStatusbarManager.setColor(Colors.transparent);
    FlutterStatusbarManager.setStyle(StatusBarStyle.LIGHT_CONTENT);
    Future.delayed(Duration(seconds: 0), () {
      VersionService.check();
      EventBus().on("newVersionTips", (arg) {
        showDialog(
          context: context,
          builder: (ctx) => Padding(
            padding: EdgeInsets.all(ScreenUtil().setWidth(8)),
            child: CustomDialog(
              bgColor: themeModel.customThemeData.mainBackgroundColor,
              txtColor: themeModel.customThemeData.mainTextColor,
              confirmButtonText: "更新",
              title: arg['tips'],
              confirm: () {
                Fluttertoast.showToast(msg: "开始后台下载更新");
                HttpManager().download(arg['downloadUrl'],
                    fileName: "install.apk", progressCallback: (v, p) {
                  var percent = ((v / p) * 100).toStringAsFixed(2) + "%";
                  _showProgressNotification(p, v, percent);
                  if (v == p) {
                    installApk("install.apk");
                  }
                });
                Navigator.pop(context);
              },
            ),
          ),
        );
      });
    });
  }

  Future<void> installApk(String path) async {
    String _path = await HttpManager().getBasesPath();
    String _apkFilePath = _path + path;
    if (_apkFilePath.isEmpty) {
      print('make sure the apk file is set');
      return;
    }
    InstallPlugin.installApk(_apkFilePath, AppConfig.APP_ID).then((result) {
      print('install apk $result');
    }).catchError((error) {
      print('install apk error: $error');
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
    themeModel = Provider.of<ThemeModel>(context);
    FlutterStatusbarManager.setColor(themeModel.customThemeData.mainColor);
//    themeModel.switchTheme(brightness: Brightness.dark);
    // TODO: implement build
    return Scaffold(
      body: WillPopScope(
        onWillPop: _willPopHandle,
        child: PageView.builder(
          onPageChanged: (int index) {
            setState(() {
              if (_currentIndex != index) {
                _currentIndex = index;
              }
            });
          },
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (BuildContext context, int index) {
            return _listPage[index];
          },
          itemCount: _listPage.length,
        ),
      ),
    );
  }

  Future<bool> _willPopHandle() async {
    if (_lastPressed == null ||
        DateTime.now().difference(_lastPressed) > Duration(seconds: 1)) {
      Fluttertoast.showToast(
          msg: "再次返回退出AnyReader", toastLength: Toast.LENGTH_SHORT);
      _lastPressed = DateTime.now();
      return Future.value(false);
    }
    return Future.value(true);
  }
}
//
//bottomNavigationBar: BottomNavigationBar(
//backgroundColor: themeModel.customThemeData.mainColor,
//selectedItemColor: themeModel.customThemeData.mainTextColor,
//unselectedItemColor: themeModel.customThemeData.mainUnActiveColor,
//items: const <BottomNavigationBarItem>[
//BottomNavigationBarItem(
//icon: Icon(IconData(0xe69e, fontFamily: 'iconfont_icon')),
//title: Text('书架'),
//),
//BottomNavigationBarItem(
//icon: Icon(IconData(0xe686, fontFamily: 'iconfont_icon')),
//title: Text('发现'),
//)
//],
//currentIndex: _currentIndex,
//onTap: (int index) {
//setState(() {
//_pageController.animateToPage(index,
//duration: Duration(milliseconds: 200), curve: Curves.easeInOut);
//});
//},
//selectedFontSize: 12,
//unselectedFontSize: 10,
//),
